import { formatTimeYMD } from "../../utils/util";
import msg from "../../utils/msg";
import { dailySign, dailySignDetail, judgeLeave, judgeLeaveSave } from "../../utils/request/api";
import User from "../../utils/user";
import { dailySignCourse } from "../curriculum/interface";
import { leaveHisroty } from "../user/leave/leaveHistory/leaveHistory";
import { sr_data } from "../user/s_worker/util";
import { url } from "../../utils/request/route";
var user = new User;
interface courseDetail{ [key: number]: sr_data[] }
// pages/admin/admin.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user:user,
    //辅导员与学生工作者端
    dailySign: {
      data: [] as dailySignCourse[],
      date:formatTimeYMD(new Date()),
      showDate:false,
      nowDate:formatTimeYMD(new Date()),
      minDate:'',
    },
    courseDetail: '' as string,
    //
    leave: {
      showData: {} as { data: Array<leaveHisroty>, today_count: number, wait_count: number },
      detailShow: false,
      index: 0,
      url: url,
      JudgeNote: '',
    },
  },
  onClickLeft(){
    wx.navigateBack();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  //管理员端初始化数据
  init_admin: async function () {
    msg.Loading('加载中');
    await dailySign({ nowDay: '',grade:user.grade })
      .then((res: any) => {
        if (res.data.code == '201') {
          msg.show(res.data.data, '');
        }
        else if (res.data.code == '200') {
          let data: dailySignCourse[] = res.data.data.course;
          this.setData({
            ['dailySign.data']: data.sort((n1, n2) => {return Number(n2.absent+n2.normal+n2.late) - Number(n1.absent+n2.normal+n2.late)}),
            //courseDetail: res.data.data.detail,
            ['dailySign.minDate']:res.data.data.startDate,
          })
        }
      });
    await judgeLeave({})
      .then((res: any) => {
        this.setData({
          ['leave.showData']: res.data.data,
        });
      });
    msg.hideLoading();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
    if (user.isAdmin) {
      //查看的是今日签到情况就更新，昨日的就不更新
      if(this.data.dailySign.date==formatTimeYMD(new Date()))
        this.init_admin();
      return;
    }
  },
  //辅导员与学生工作者端：
  chooseDate(){
    this.setData({
      ['dailySign.showDate']: true,
    })
  },
  onCloseCalendar(){
    this.setData({
      ['dailySign.showDate']: false,
    })
  },
  onConfirmCalendar:async function(e:any){
    this.setData({
      ['dailySign.date']: e.detail.value,
    });
    msg.Loading('加载中');
    await dailySign({ nowDay: e.detail.value,grade:user.grade })
      .then((res: any) => {
        msg.hideLoading();
        if (res.data.code == '201') {
          msg.show(res.data.data, '');
        }
        else if (res.data.code == '200') {
          let data: dailySignCourse[] = res.data.data.course;
          this.setData({
            ['dailySign.data']: data.sort((n1, n2) => {return Number(n2.absent+n2.normal+n2.late) - Number(n1.absent+n2.normal+n2.late)}),
            ['dailySign.minDate']:res.data.data.startDate,
          })
        }
      });
      msg.hideLoading();
    this.onCloseCalendar();
  },
  changeActive2(e: any) {
    let index = e.detail.index;
    let data = this.data.dailySign.data;
    if (index == 0) {
      //默认排序
      this.setData({
        ['dailySign.data']: data.sort((n1, n2) => {return Number(n2.absent+n2.normal+n2.late) - Number(n1.absent+n2.normal+n2.late)}),
      })
    }
    else if (index == 1) {
      //签到率
      this.setData({
        ['dailySign.data']: data.sort((n1, n2) => {return Number(n2.signRate) - Number(n1.signRate)}),
        
      })
    }
    else if (index == 2) {
      //缺勤率
      this.setData({
        ['dailySign.data']: data.sort((n1, n2) => {return Number(n1.signRate) - Number(n2.signRate)}),
      })
    }
  },
  goToDailySign:async function(e: any) {
    let course_id = e.currentTarget.dataset.course_id;
    let course ={} as dailySignCourse;
    let signDetail:sr_data[]=await dailySignDetail({course_id:course_id,date:this.data.dailySign.date})
    .then((res:any)=>{
      return res.data.data;
    })
    .catch((err)=>{
      console.log('err=',err);
    })
    ;
    //let courseDetail:courseDetail=JSON.parse(this.data.courseDetail);
    //let signDetail = courseDetail[course_id];
    let courseInfo={
      name:signDetail[0].c_name,
      time:'第'+signDetail[0].week+'周 星期'+signDetail[0].c_day+' 第'+signDetail[0].c_time+'节',
    }
    wx.navigateTo({
      url: '/pages/dailySign/dailySign?signDetail=' + JSON.stringify(signDetail)+'&courseInfo='+JSON.stringify(courseInfo),
    });
  },
  //数组排序
  _sortBy(attr: any, rev: number) {
    //第二个参数没有传递 默认升序排列
    if (rev == undefined) {
      rev = 1;
    } else {
      rev = (rev) ? 1 : -1;
    }
    return function (a: any, b: any) {
      a = a[attr];
      b = b[attr];
      if (a < b) {
        return rev * -1;
      }
      if (a > b) {
        return rev * 1;
      }
      return 0;
    }//arr.sort(sortBy("name",false))
  },

  //请假相关事件
  showLeaveDetail(e: any) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      ['leave.index']: index,
      ['leave.detailShow']: true,
    })
  },
  inputNote(e: any) {
    let input = e.detail.value;
    this.setData({
      ['leave.JudgeNote']: input,
    })
  },
  onClose() {
    this.setData({
      ['leave.detailShow']: false,
    })
  },
  judge: async function (e: any) {
    let state = e.currentTarget.dataset.state;
    let id = e.currentTarget.dataset.id;
    let flag = -1;
    if (state == 'success') flag = 1;
    else if (state == 'fail') flag = 0;
    else {
      msg.show('程序错误', '请联系管理员修复'); return;
    }
    msg.Loading('上传中');
    await judgeLeaveSave({ flag: flag, leave_id: id, judgeNote: this.data.leave.JudgeNote,openid:this.data.user.openid })
      .then((res: any) => {
        if (res.data.code == '200') {
          msg.show('保存成功', '');
        }
        else msg.show('出错了', '请稍后再试');
      })
      .catch((err: any) => {
      });
    msg.hideLoading();
    let data = this.data.leave.showData.data;
    let index = 0;
    data.forEach((item, index2) => {
      if (item.id == id) {
        index = index2;
      }
    })
    data.splice(index, 1);
    this.setData({
      ['leave.detailShow']: false,
      ['leave.showData.data']: data,
      ['leave.JudgeNote']: '',
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})